<script setup lang="ts">
import { defineExpose, onMounted, onUnmounted, ref, watch } from 'vue'
import browser from 'webextension-polyfill'
import { getChannelIdFromUrl, isYouTubeChannelPage } from '~/logic/youtube-channel'
import { useWebExtensionStorage } from '~/composables/useWebExtensionStorage'
import { useAuth } from '~/composables/useAuth'
import { API_ENDPOINTS, ENV } from '~/env'
import { AuthenticatedApiClient } from '~/utils/api-auth'

// 类型定义
type ReportType =
  | 'fake_data'
  | 'violation'
  | 'breach_contract'
  | 'bad_attitude'
  | 'plagiarism'
  | 'negative_public_opinion'
  | 'overpricing'
  | 'impersonation'
  | 'private_deal'

// 状态管理
const isYouTubeChannel = ref(false)
const error = ref<string | null>(null)
const { data: channelId } = useWebExtensionStorage<string | null>('currentChannelId', null)
const reportCount = ref(0) // 添加举报次数状态
const isSubmitting = ref(false)

// 认证信息
const { isAuthenticated, currentToken } = useAuth()

// 举报对话框状态
const showReportDialog = ref(false)
const reportType = ref<ReportType | ''>('')
const reportDescription = ref('')

defineExpose({
  openReportDialog,
  openSidebar,
  submitReport,
})

// 举报对话框相关方法
function openReportDialog() {
  showReportDialog.value = true
}

function closeReportDialog() {
  showReportDialog.value = false
  reportType.value = ''
  reportDescription.value = ''
}

// 打开侧边栏
async function openSidebar() {
  try {
    if (!channelId.value) {
      return
    }

    await browser.runtime.sendMessage({
      action: 'openSidebar',
      channelId: channelId.value,
    })
  }
  catch {
    // 可以在这里添加用户提示
  }
}

async function submitReport() {
  if (isSubmitting.value)
    return

  if (!isAuthenticated.value) {
    // eslint-disable-next-line no-alert
    alert('请先登录后再进行举报')
    return
  }

  if (!reportType.value) {
    // eslint-disable-next-line no-alert
    alert('请选择举报类型')
    return
  }

  if (!channelId.value) {
    // eslint-disable-next-line no-alert
    alert('无法获取当前频道信息，举报失败')
    return
  }

  isSubmitting.value = true

  try {
    // 构造 multipart/form-data
    const formData = new FormData()
    // 约定：1 代表 YouTube，可根据后端实际枚举调整
    formData.append('platform_id', '1')
    formData.append('platform_user_id', channelId.value)
    formData.append('type', reportType.value as string)
    formData.append('content', reportDescription.value || '')
    formData.append('evidence', '')

    const headers: Record<string, string> = {}
    if (currentToken.value)
      headers.Authorization = `Bearer ${currentToken.value}`

    const res = await fetch(API_ENDPOINTS.CREATE_REPORT(), {
      method: 'POST',
      headers,
      body: formData,
    })

    if (!res.ok) {
      const msg = await res.text()
      throw new Error(msg || `请求失败，状态码 ${res.status}`)
    }

    // 成功后刷新举报次数
    if (channelId.value)
      await fetchReportCount(channelId.value)

    // eslint-disable-next-line no-alert
    alert('举报成功，感谢您对网络环境的贡献！')
    closeReportDialog()
  }
  catch (err) {
    console.error('举报失败:', err)
    // eslint-disable-next-line no-alert
    alert(`举报失败：${(err as Error).message}`)
  }
  finally {
    isSubmitting.value = false
  }
}

// 查询举报次数
async function fetchReportCount(_id: string) {
  try {
    const apiClient = new AuthenticatedApiClient(ENV.API_BASE_URL)
    const res = await apiClient.get(`/reports/count?platform_user_id=${encodeURIComponent(_id)}`)
    const result = await res.json()
    if (result.success && result.data && typeof result.data.report_count === 'number')
      reportCount.value = result.data.report_count
    else
      reportCount.value = 0

    error.value = null
  }
  catch (err) {
    console.error('Failed to fetch report count:', err)
    error.value = '获取举报次数失败'
  }
}

// 页面变化处理
function handlePageChange() {
  try {
    isYouTubeChannel.value = isYouTubeChannelPage()

    // 仅在频道页时才获取并保存频道 ID，否则设为 null，避免无效请求
    const newChannelId = isYouTubeChannel.value ? getChannelIdFromUrl() : null
    channelId.value = newChannelId

    // 判断是否是 YouTube 频道页面
    if (!isYouTubeChannel.value) {
      // 若不是频道页，重置举报计数
      reportCount.value = 0
    }
  }
  catch {
    error.value = 'Failed to initialize YouTube extension'
  }
}

// URL 变化监听
function listenUrlChange(callback: () => void) {
  let lastUrl = location.href
  const observer = new MutationObserver(() => {
    if (location.href !== lastUrl) {
      lastUrl = location.href
      // 2秒后执行
      setTimeout(() => {
        callback()
      }, 1000)
    }
  })

  observer.observe(document, { subtree: true, childList: true })

  const _wr = (type: 'pushState' | 'replaceState') => {
    const orig = history[type]
    return function (this: History, ...args: any[]) {
      // @ts-expect-error 历史原因，需要保持兼容性
      const rv = orig.apply(this, args)
      window.dispatchEvent(new Event(type))
      window.dispatchEvent(new Event('urlchange'))
      return rv
    }
  }

  history.pushState = _wr('pushState')
  history.replaceState = _wr('replaceState')
  window.addEventListener('popstate', () => window.dispatchEvent(new Event('urlchange')))
  window.addEventListener('urlchange', callback)

  // 返回清理函数
  return () => {
    observer.disconnect()
    window.removeEventListener('popstate', () => window.dispatchEvent(new Event('urlchange')))
    window.removeEventListener('urlchange', callback)
  }
}

// 生命周期钩子
let cleanup: (() => void) | null = null

// 监听 currentChannelId
watch(channelId, (newId: string | null) => {
  // 切换频道时，先重置为 0，确保界面能及时更新
  reportCount.value = 0

  // 如果存在新的频道 ID，再去查询实际举报次数
  if (newId)
    fetchReportCount(newId)
})

onMounted(() => {
  handlePageChange()
  cleanup = listenUrlChange(handlePageChange)
})

onUnmounted(() => {
  if (cleanup) {
    cleanup()
  }
})
</script>

<template>
  <div class="youtube-channel-extension">
    <div v-if="isYouTubeChannel" class="youtube-channel-extension-content">
      <!-- 举报状态横幅 -->
      <div v-if="reportCount > 0" class="report-banner report-banner-red">
        该频道已被举报 {{ reportCount }} 次
      </div>
      <div v-else class="report-banner report-banner-green">
        该频道未被举报
      </div>

      <!-- 信息区：举报记录 -->
      <div class="report-link-container">
        <button class="report-link-btn" type="button" @click="openSidebar">
          查看详细举报记录
        </button>
      </div>

      <!-- 操作区：举报按钮 -->
      <div class="report-button-container">
        <button class="report-button" @click="openReportDialog">
          我要举报该频道
        </button>
      </div>
    </div>

    <div v-if="showReportDialog" class="report-dialog-backdrop" @click.self="closeReportDialog">
      <div class="report-dialog" @keydown.stop @keyup.stop @keypress.stop>
        <h3>举报频道</h3>
        <label>
          举报类型：
          <select v-model="reportType">
            <option value="" disabled>请选择类型</option>
            <option value="fake_data">虚假数据 / 刷量行为</option>
            <option value="breach_contract">合同违约 / 合作失信</option>
            <option value="bad_attitude">态度恶劣 / 沟通困难</option>
            <option value="plagiarism">抄袭 / 原创性问题</option>
            <option value="negative_public_opinion">负面舆情 / 公关风险</option>
            <option value="overpricing">收费虚高 / 性价比低</option>
            <option value="impersonation">代运营冒充本人</option>
            <option value="private_deal">诱导私下交易 / 财务风险</option>
          </select>
        </label>
        <label>
          描述：
          <textarea v-model="reportDescription" placeholder="请描述举报原因" />
        </label>
        <div class="dialog-actions">
          <button @click="submitReport">
            提交
          </button>
          <button @click="closeReportDialog">
            取消
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.youtube-channel-extension-content {
  position: fixed;
  top: 50%;
  right: 20px;
  transform: translateY(-50%);
  z-index: 9999;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 0;
  background: rgba(255, 255, 255, 0.98);
  padding: 12px 10px 10px 10px;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.13);
  min-width: 160px;
  max-width: 200px;
  border: 1px solid rgba(211, 208, 208, 0.13);
}

.report-banner {
  width: 100%;
  font-size: 13px;
  font-weight: 600;
  padding: 7px 0;
  border-radius: 8px 8px 0 0;
  text-align: center;
  margin-bottom: 6px;
  letter-spacing: 0.2px;
}

.report-banner-red {
  color: #c62828;
  background: #ffeaea;
  border-bottom: 1px solid #f8bdbd;
}

.report-banner-green {
  color: #388e3c;
  background: #e8f5e9;
  border-bottom: 1px solid #b7e1c2;
}

.report-link-container {
  width: 100%;
  display: flex;
  justify-content: center;
  margin-bottom: 10px;
}

.report-link-btn {
  background: #0f0f0f;
  border: none;
  color: #ffffff;
  font-size: 13px;
  cursor: pointer;
  padding: 7px 14px;
  border-radius: 7px;
  font-weight: 600;
  text-decoration: none;
  transition: background 0.2s, transform 0.2s;
}
.report-link-btn:hover {
  background: #272727;
  transform: translateY(-1px) scale(1.03);
}
.report-link-btn:active {
  background: #000000;
  transform: translateY(0) scale(1);
}

.report-button-container {
  width: 100%;
  display: flex;
  justify-content: center;
}

.report-button {
  background: #d32f2f;
  color: #fff;
  border: none;
  padding: 7px 14px;
  border-radius: 7px;
  font-size: 13px;
  font-weight: 600;
  cursor: pointer;
  box-shadow: 0 1px 4px rgba(211, 47, 47, 0.08);
  transition: background 0.2s, transform 0.2s;
}
.report-button:hover {
  background: #b71c1c;
  transform: translateY(-1px) scale(1.03);
}
.report-button:active {
  background: #880808;
  transform: translateY(0) scale(1);
}

.report-dialog-backdrop {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.4);
  z-index: 9999;
  display: flex;
  align-items: center;
  justify-content: center;
}

.report-dialog {
  background: #fff;
  border-radius: 8px;
  padding: 24px 20px 16px 20px;
  min-width: 320px;
  box-shadow: 0 4px 24px rgba(0, 0, 0, 0.18);
}

.report-dialog h3 {
  margin-top: 0;
  margin-bottom: 16px;
  font-size: 18px;
}

.report-dialog label {
  display: block;
  margin-bottom: 12px;
  font-size: 14px;
}

.report-dialog select,
.report-dialog textarea {
  width: 100%;
  margin-top: 4px;
  margin-bottom: 8px;
  padding: 6px;
  font-size: 14px;
  border-radius: 4px;
  border: 1px solid #ccc;
  box-sizing: border-box;
}

.report-dialog textarea {
  min-height: 60px;
  resize: vertical;
}

.dialog-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.dialog-actions button {
  padding: 6px 18px;
  border-radius: 4px;
  border: none;
  background: #0f0f0f;
  color: #fff;
  cursor: pointer;
  font-size: 14px;
  transition: background 0.2s;
}

.dialog-actions button:hover {
  background: #272727;
}
</style>
